//
//  CoreDataToolHelper.m
//  We_Travel
//
//  Created by lanou3g on 15/12/21.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "CoreDataToolHelper.h"
#import "AppDelegate.h"
#import "Country.h"
#import "Site.h"
#import "Area.h"
#import "Place.h"
#import "AllModel.h"

@interface CoreDataToolHelper ()
//数据管理器类
@property (nonatomic,strong) NSManagedObjectContext *contex;
//实体描述类
@property (nonatomic,strong) NSEntityDescription *countryDescription;
@property (nonatomic,strong) NSEntityDescription *placeDescription;
@property (nonatomic,strong) NSEntityDescription *areaDescription;
@property (nonatomic,strong) NSEntityDescription *siteDescription;
@end

@implementation CoreDataToolHelper
//单例
+ (instancetype)shareCoreDataTool{
    static CoreDataToolHelper *coreDataToolHelper = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        coreDataToolHelper = [[CoreDataToolHelper alloc]init];
        [coreDataToolHelper setupCoreData];
    });
    return coreDataToolHelper;
}
//设置CoreData
- (void)setupCoreData{
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    self.contex = appDelegate.managedObjectContext;
    self.placeDescription = [NSEntityDescription entityForName:@"Place" inManagedObjectContext:self.contex];
    self.areaDescription = [NSEntityDescription entityForName:@"Area" inManagedObjectContext:self.contex];
    self.countryDescription = [NSEntityDescription entityForName:@"Country" inManagedObjectContext:self.contex];
    self.siteDescription = [NSEntityDescription entityForName:@"Site" inManagedObjectContext:self.contex];
}
/**
 *  添加城市,即添加行程
 *
 *  @param countryName
 *  @param countryID
 */
- (void)addTravelCountryName:(NSString *)countryName CountryID:(NSInteger)countryID{
    Country *country = [[Country alloc]initWithEntity:self.countryDescription insertIntoManagedObjectContext:self.contex];
    country.countryName = countryName;
    country.countryID = [NSString stringWithFormat:@"%ld",countryID];
    //  country的起始地点
    Place *place = [[Place alloc]initWithEntity:self.placeDescription insertIntoManagedObjectContext:self.contex];
    place.startPlace = @"北京";
    place.stopPlace = @"北京";
    place.country = country;
    [self.contex save:nil];
}
/**
 *  获取Country第几个行程
 */
- (Country *)fetchCountryEntityByCount:(NSInteger)count{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    [fetchRequest setEntity:self.countryDescription];
    NSError *error = nil;
    NSArray *fetchResult = [self.contex executeFetchRequest:fetchRequest error:&error];
    if (error) {
        NSLog(@"查询出错error = %@",error);
    }
    if (fetchResult.count-1 >= count) {
        Country *country = fetchResult[count];
        return country;
    }else{
        //NSLog(@"没有这个行程");
        return nil;
    }
}
//获取country的所有行程
- (NSArray *)fetchCountry{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    [fetchRequest setEntity:self.countryDescription];
    NSError *error = nil;
    NSArray *fetchResult = [self.contex executeFetchRequest:fetchRequest error:&error];
    if (error) {
        NSLog(@"查询出错error = %@",error);
    }
    return fetchResult;
}
//获取起始地区
- (Place *)fetchPlaceByCount:(NSInteger)count{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    [fetchRequest setEntity:self.placeDescription];
    NSError *error = nil;
    NSArray *fetchResult = [self.contex executeFetchRequest:fetchRequest error:&error];
    if (error) {
        NSLog(@"查询出错error = %@",error);
    }
    if (fetchResult.count-1 >= count) {
       Place *place = fetchResult[count];
        return place;
    }else{
       // NSLog(@"没有这个行程");
        return nil;
    }
}
//修改起始地区
- (void)changeStartPlace:(NSString *)startPlace StopPlace:(NSString *)stopPlace CountryCount:(NSInteger)count{
   Place *place = [self fetchPlaceByCount:count];
    place.startPlace = startPlace;
    place.stopPlace = stopPlace;
    [self.contex save:nil];
}
//修改开始地区
- (void)changeStartPlace:(NSString *)startPlace CountryCount:(NSInteger)count{
    Place *place = [self fetchPlaceByCount:count];
    place.startPlace = startPlace;
    [self.contex save:nil];
}
//修改结束地区
- (void)changeStopPlace:(NSString *)stopPlace CountryCount:(NSInteger)count{
    Place *place = [self fetchPlaceByCount:count];
     place.stopPlace = stopPlace;
    [self.contex save:nil];
}
//修改开始时间
- (void)changeStartTime:(NSString *)startTime CountryCount:(NSInteger)count{
    Place *place = [self fetchPlaceByCount:count];
    place.startTime = startTime;
    [self.contex save:nil];
}
/**
 *  添加地区,即给行程添加地区
 */
- (void)addTravelAreaName:(NSString *)areaName AreaID:(NSInteger)areaID areaDay:(NSInteger)areaDay CountryCount:(NSInteger)count{
    Area *area = [[Area alloc]initWithEntity:self.areaDescription insertIntoManagedObjectContext:self.contex];
    area.areaName = areaName;
    area.areaID = [NSString stringWithFormat:@"%ld",areaID];
    area.areaDay =[NSString stringWithFormat:@"%ld",areaDay];
    area.country =[self fetchCountryEntityByCount:count];
    [self.contex save:nil];
}
/**
 *  根据Country获取area
 *
 */
- (NSArray *)fetchAreaByCountryCount:(NSInteger)countryCount{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    [fetchRequest setEntity:self.areaDescription];
    Country *country = [self fetchCountryEntityByCount:countryCount];
    NSError *error = nil;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"country == %@",country];
    [fetchRequest setPredicate:predicate];
    [fetchRequest setReturnsObjectsAsFaults:NO];
     NSArray *fetchResult = [self.contex executeFetchRequest:fetchRequest error:&error];
    
//    NSMutableArray *areas = [NSMutableArray array];
//    for (Area *area in fetchResult) {
//        if ([country.area.allObjects containsObject:area]) {
//            [areas addObject:area];
//        }
//    }
    
    if (error) {
        NSLog(@"查询出错error = %@",error);
    }
    if (fetchResult.count == 0) {
      //  NSLog(@"然而这个行程并没有这个地区");
        return nil;
    }
    return fetchResult;
}
/**
 *  获取area实体
 *
 */
- (Area *)fetchAreaByCount:(NSInteger)count CountryCount:(NSInteger)countryCount{
    NSArray *array = [self fetchAreaByCountryCount:countryCount];
    Area *area = array[count];
    return area;
}
/**
 *  添加景点,即给每个地区添加景点
 */
- (void)addTravelSiteName:(NSString *)siteName siteID:(NSInteger)siteID Sitetime:(NSString *)time SiteDay:(NSInteger)siteDay AreaCount:(NSInteger)areaCount CountryCount:(NSInteger)countryCount{
    Site *site = [[Site alloc]initWithEntity:self.siteDescription insertIntoManagedObjectContext:self.contex];
    site.siteName = siteName;
    site.siteID = [NSString stringWithFormat:@"%ld",siteID];
    site.day = [NSString stringWithFormat:@"%ld",siteDay];
    site.time = time;
    Area *area = [self fetchAreaByCount:areaCount CountryCount:countryCount];
    if (area) {
        site.area = area;
        [self.contex save:nil];
    }
}
/**
 *  通过day获取site数组
 */
- (NSArray *)fetchSiteDay:(NSInteger)siteDay AreaCount:(NSInteger)areaCount CountryCount:(NSInteger)countryCount{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    Area *area = [self fetchAreaByCount:areaCount CountryCount:countryCount];
    if (!area) {
      //  NSLog(@"然而这个行程并没有这个地区");
        return nil;
    }else{
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"area == %@ && day == %@",area,[NSString stringWithFormat:@"%ld",siteDay]];
        [fetchRequest setPredicate:predicate];
        [fetchRequest setEntity:self.siteDescription];
        [fetchRequest setReturnsObjectsAsFaults:NO];
        NSError *error = nil;
        NSArray *fetchResult = [self.contex executeFetchRequest:fetchRequest error:&error];
        if (error) {
            NSLog(@"查询出错error = %@",error);
        }
        if (fetchResult.count == 0) {
          //  NSLog(@"然而这个地区行程中第%ld天并没有景点",siteDay+1);
            return nil;
        }
        return fetchResult;
    }
}
/**
 *  通过time(am,pm,night)获取site实体数组
 */
- (NSArray *)fetchSiteTime:(NSString *)siteTime SiteDay:(NSInteger)siteDay AreaCount:(NSInteger)areaCount CountryCount:(NSInteger)countryCount{
    NSArray *array = [self fetchSiteDay:siteDay AreaCount:areaCount CountryCount:countryCount];
    NSMutableArray *fetchResult = [NSMutableArray array];
    if (array.count <= 0) {
       // NSLog(@"然而这一天没有景点游览");
        return nil;
    }else{
        for (Site *si in array) {
            if ([si.time isEqualToString:siteTime]) {
                [fetchResult addObject:si];
            }
        }
        return fetchResult;
    }
}
/**
 *  根据siteDay删除满足条件的所有site
*/
- (void)deleteTravelSiteDay:(NSInteger)siteDay AreaCount:(NSInteger)areaCount CountryCount:(NSInteger)countryCount{
    NSArray *sites = [self fetchSiteDay:siteDay AreaCount:areaCount CountryCount:countryCount];
    for (Site *s in sites) {
        [self.contex deleteObject:s];
    }
    [self.contex save:nil];
}
/**
 *  根据siteTime删除满足条件的所有site
 */
- (void)deleteTravelSiteTime:(NSString *)siteTime SiteDay:(NSInteger)siteDay AreaCount:(NSInteger)areaCount CountryCount:(NSInteger)countryCount{
    NSArray *sites = [self fetchSiteTime:siteTime SiteDay:siteDay AreaCount:areaCount CountryCount:countryCount];
    for (Site *site in sites) {
        [self.contex deleteObject:site];
    }
    [self.contex save:nil];
}
/**
 *  删除单个site景点
 *
 */
- (void)deleteTravelSiteTime:(NSString *)siteTime SiteCount:(NSInteger)siteCount SiteDay:(NSInteger)siteDay AreaCount:(NSInteger)areaCount CountryCount:(NSInteger)countryCount{
    NSArray *sites = [self fetchSiteTime:siteTime SiteDay:siteDay AreaCount:areaCount CountryCount:countryCount];
    Site *site = sites[siteCount];
    [self.contex deleteObject:site];
    [self.contex save:nil];
}
/**
 *  删除单个area地区
 *
 */
- (void)deleteTravelAreaCount:(NSInteger)areaCount CountryCount:(NSInteger)countryCount{
    Area *area = [self fetchAreaByCount:areaCount CountryCount:countryCount];
    [self.contex deleteObject:area];
    [self.contex save:nil];
}
/**
 *  删除所有地区
 */
- (void)deleteTravelAreaAllCountryCount:(NSInteger)countryCount{
    NSArray *array = [self fetchAreaByCountryCount:countryCount];
    for (Area *a in array) {
        [self.contex deleteObject:a];
    }
    [self.contex save:nil];
}
/**
 *  删除Country国家行程
 */
- (void)deleteTravelCountry:(NSInteger)count{
    Country *country = [self fetchCountryEntityByCount:count];
    [self.contex deleteObject:country];
    [self.contex save:nil];
}
/**
 *  获取所有的sites
 */
- (NSArray *)fetchSitesAllAreaCount:(NSInteger)areaCount CountryCount:(NSInteger)countryCount{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    Area *area = [self fetchAreaByCount:areaCount CountryCount:countryCount];
    if (!area) {
       // NSLog(@"然而这个行程并没有这个地区");
        return nil;
    }else{
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"area == %@",area];
        [fetchRequest setPredicate:predicate];
        [fetchRequest setEntity:self.siteDescription];
        [fetchRequest setReturnsObjectsAsFaults:NO];
        NSError *error = nil;
        NSArray *fetchResult = [self.contex executeFetchRequest:fetchRequest error:&error];
        if (error) {
            NSLog(@"查询出错error = %@",error);
        }
        if (fetchResult.count == 0) {
          //  NSLog(@"然而这个地区行程中没有景点");
            return nil;
        }
        return fetchResult;
    }
}
/**
 *  按name排序,给area
 */
- (void)sortAreaByidArray:(NSMutableArray *)idArray CountryCount:(NSInteger)countryCount{
   NSArray *array = [self fetchAreaByCountryCount:countryCount];
    NSInteger count = array.count;
        for (int j = 0; j < idArray.count; j++) {
            for (int i = 0; i < count; i++) {
                Area *area = array[i];
                if ([area.areaName isEqualToString:idArray[j]]) {
                    [self addTravelAreaName:area.areaName AreaID:[area.areaID integerValue] areaDay:[area.areaDay integerValue] CountryCount:countryCount];
                    NSArray *sites = [self fetchSitesAllAreaCount:i CountryCount:countryCount];
                    for (Site *site in sites) {
                        [self addTravelSiteName:site.siteName siteID:[site.siteID integerValue] Sitetime:site.time SiteDay:[site.day integerValue] AreaCount:array.count + j CountryCount:countryCount];
                    }
                }
            }
        }
        for (int k = 0; k < count; k ++) {
        [self deleteTravelAreaCount:0 CountryCount:countryCount];
        }
    [self.contex save:nil];
}
@end









